package honeypot.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletResponseAware;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import cm.util.hibernate.HibernateSessionFactory;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport implements ServletResponseAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String username;
	private String password;
	private Session h_session;
    private Transaction trans;
    private String hql;
    private Query query;
    private HttpServletResponse response;
    
	public String getUsername() {
		return username;
	}


	public void setUsername(String username) {
		this.username = username;
	}


	public String getPassword() {
		return password;
	}


	public void setPassword(String password) {
		this.password = password;
	}


	public Session getSession() {
		return h_session;
	}


	public void setSession(Session h_session) {
		this.h_session = h_session;
	}


	public Transaction getTrans() {
		return trans;
	}


	public void setTrans(Transaction trans) {
		this.trans = trans;
	}


	public String getHql() {
		return hql;
	}


	public void setHql(String hql) {
		this.hql = hql;
	}


	public Query getQuery() {
		return query;
	}


	public void setQuery(Query query) {
		this.query = query;
	}
     public void setServletResponse(HttpServletResponse response)
       {
     	  this.response=response;
       }

	public String execute() throws Exception
	{
	
		  h_session=HibernateSessionFactory.getSession();
		  trans=h_session.beginTransaction();
		  hql="select user from User as user where user.username=:u and user.password=:p";
		  query=h_session.createQuery(hql);
		  query.setString("u",username);//设置查询参数
		  query.setString("p",password);//设置查询参数

          List l=query.list();
     	  if((l==null)||(l.size()<=0))
     	  {
     		 this.addFieldError("用户","密码错误或者用户不存在!");
			  
			  return "false";
     	  }
        
     	  Cookie cookie=new Cookie("username",this.getUsername());
     	  cookie.setMaxAge(2000);
     	  response.addCookie(cookie);
//     	  HttpSession session=null;
//     	  session.setAttribute("user", this.getUsername());
     	  ActionContext.getContext().getSession().put("user",this.getUsername());
     	  
     	  h_session.close();
		  return "success";
	}
	  
}
